package com.xiaoming.e3mall.controller;

import com.xiaoming.e3mall.common.pojo.EasyUIDataGridResult;
import com.xiaoming.e3mall.common.utils.E3Result;
import com.xiaoming.e3mall.pojo.TbItem;
import com.xiaoming.e3mall.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

@Controller
public class ItemController {

    @Autowired
    private ItemService itemService;

    @Autowired
    private JmsTemplate jmsTemplate; //生产者

    @Resource(name = "topicDestination") //广播消费者
    private Destination destination;

    /**
     * 根据id查询商品
     */
    @RequestMapping("/item/{itemId}")
    @ResponseBody
    public TbItem getItemById(@PathVariable Long itemId) {
        TbItem tbItem = itemService.getItemById(itemId);
        return tbItem;
    }

    /**
     * 查询商品列表并分页
     */


    @RequestMapping("/item/list")
    @ResponseBody
    public EasyUIDataGridResult getItemList(Integer page, Integer rows) {
        //调用dubbo发布的服务  查询商品列表
        EasyUIDataGridResult result = itemService.getItemList(page, rows);
        return result;
    }


    /**
     * 商品添加功能
     */
    @RequestMapping(value = "/item/save", method = {RequestMethod.POST})
    @ResponseBody
    public E3Result addItem(TbItem item, String desc) {
        E3Result e3Result = itemService.addItem(item, desc);
        /**
         *  发送mq消息给search服务,之所以在Controller中发送,是为了防止在Service事物未提交就发送消息的问题
         */
        //发送mq消息
        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(e3Result.getId()+"");
            }
        });
        return e3Result;
    }


}
